<template>
  <el-dialog :close-on-click-modal='false' v-drag :title="$t('配置接口')" :v-if="dialogVisible" :visible.sync="dialogVisible" width="950px" @close='close' top="10vh">
    <div class="dialogContentBox">
      <el-form ref="form" :model="record" label-width="120px" label-position="left" :rules="rules" style="margin:0 20px;">
        <el-form-item :label="$t('名称')" prop="name">
          <div>{{record.name}}</div>
        </el-form-item>
      </el-form>
      <el-form ref="form" :model="record" label-width="120px" inline label-position="left" :rules="rules" style="margin:0 20px;">
        <el-form-item :label="$t('模式')" prop="enPortMode" style="width:400px;">
          <el-radio-group v-model="record.enPortMode">
            <el-radio :label="0" class="router">{{$t('路由模式')}}</el-radio>
            <el-radio :label="1" class="trans">{{$t('透明模式')}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item :label="$t('状态')" prop="PortFlag" style="width:400px;margin-left:30px;">
          <el-radio-group v-model="record.PortFlag">
            <el-radio label="up" class="up">{{$t('开启')}}</el-radio>
            <el-radio label="down" class="down">{{$t('关闭')}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item :label="$t('链路类型')" v-if="record.enPortMode === 1" prop="PHYSICS_PORT_TYPE" style="width:400px;">
          <el-radio-group v-model="record.PHYSICS_PORT_TYPE">
            <el-radio :label="0" class="access">access</el-radio>
            <el-radio :label="1" class="trunk">trunk</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="Default VLAN Id" v-if="record.enPortMode === 1" prop="iVlanId" style="width:400px;margin-left:30px;">
          <el-input v-emoji v-model="record.iVlanId" ref="VlanId" size='small'></el-input>
        </el-form-item>
        <el-form-item label="Trunk VLAN Id" v-if="record.enPortMode === 1 && record.PHYSICS_PORT_TYPE === 1" prop="iAllowed">
          <el-input v-emoji v-model="record.iAllowed" ref="trVlanId" size='small' :style="lang==='zh'?'width:220px;':'width:300px;'" :placeholder="$t('请输入(1-4094,例如：1,3,5-10)')"></el-input>
        </el-form-item>
        <el-tabs v-model="activeName" type="card" @tab-click="handleClick" v-if="record.enPortMode === 0">
          <el-tab-pane label="IPv4" name="ipv4">
            <el-button type="success" size="small" @click="addBondIp('IPv4')" class="addIp">{{$t('添加')}}</el-button>
            <el-table size='mini' :data="record.ipv4" stripe border style="width: 100%;margin-top: 5px;">
              <el-table-column prop='cPortIpv4' label="IPv4" align="center" min-width="100">
                <template slot-scope="scope">
                  <tooltip :html="scope.row.cPortIpv4" :content="scope.row.cPortIpv4" class="wid190" :refName="scope.row.cPortIpv4">
                  </tooltip>
                </template>
              </el-table-column>
              <el-table-column prop='cPortNetmask' :label="$t('子网掩码')" align="center" min-width="100">
                <template slot-scope="scope">
                  <tooltip :html="scope.row.cPortNetmask" :content="scope.row.cPortNetmask" class="wid190" :refName="scope.row.cPortNetmask">
                  </tooltip>
                </template>
              </el-table-column>
              <el-table-column fixed="right" :label="$t('操作')" width="110" align="center">
                <template slot-scope="scope">
                  <el-button @click.native.prevent="deleteRow(scope.$index, record.ipv4)" type="danger" plain size="mini" :class="'del' + scope.$index">
                    {{$t('删除')}}
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
          <el-tab-pane label="IPv6" name="ipv6">
            <el-button type="success" size="small" @click="addBondIp('IPv6')" class="addIp">{{$t('添加')}}</el-button>
            <el-table size='mini' :data="record.ipv6" stripe border style="width: 100%;margin-top: 5px;">
              <el-table-column prop='cPortIpv6' label="IPv6" align="center" min-width="100">
                <template slot-scope="scope">
                  <tooltip :html="scope.row.cPortIpv6" :content="scope.row.cPortIpv6" class="wid190" :refName="scope.row.cPortIpv6">
                  </tooltip>
                </template>
              </el-table-column>
              <el-table-column prop='cDevIpv6Prefix' :label="$t('前缀')" align="center" min-width="100">
                <template slot-scope="scope">
                  <tooltip :html="scope.row.cDevIpv6Prefix" :content="scope.row.cDevIpv6Prefix" class="wid190" :refName="scope.row.cDevIpv6Prefix">
                  </tooltip>
                </template>
              </el-table-column>
              <el-table-column fixed="right" :label="$t('操作')" width="110" align="center">
                <template slot-scope="scope">
                  <el-button @click.native.prevent="deleteRow(scope.$index, record.ipv6)" type="danger" plain size="mini" :class="'del' + scope.$index">
                    {{$t('删除')}}
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
        </el-tabs>

        <bond-ip-dialog ref="refBondIpDialogVisible" @addBondIpForTable='addBondIpForTable'></bond-ip-dialog>
      </el-form>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submit" class="addSubmit">{{$t('确 定')}}</el-button>
      <el-button @click="close" class="addClose">{{$t('取 消')}}</el-button>
    </span>
  </el-dialog>
</template>
<script>
import { setBondInfo, getBondInfo } from '@/api/network/api/bond'
import BondIpDialog from './BondIpDialog'
import { inputClass } from '@/utils/input-class.js'
export default {
  name: 'BondDialog',
  components: {
    BondIpDialog
  },
  data () {
    var validateName = (rule, value, callback) => {
      if (String(value).trim() === '') {
        callback(new Error(this.$t('不能为空')))
      } else {
        callback()
      }
    }

    return {
      lang: this.$i18n.locale,
      dialogVisible: false,
      record: {
        id: null,
        name: '',
        enPortMode: 0,
        PortFlag: 'up',
        ipv4: [], // cPortIpv4 cPortNetmask
        ipv6: [], // cPortIpv6 cDevIpv6Prefix
        PHYSICS_PORT_TYPE: 0,
        iVlanId: '',
        iAllowed: ''
      },
      recordCopy: {
        id: null,
        name: '',
        enPortMode: 0,
        PortFlag: 'up',
        ipv4: [],
        ipv6: [],
        PHYSICS_PORT_TYPE: 0,
        iVlanId: '',
        iAllowed: ''
      },
      activeName: 'ipv4',
      rules: {
        name: [{ required: false, validator: validateName, trigger: 'blur' }],
        iVlanId: [{ required: false, validator: validateName, trigger: 'blur' }]
      }
    }
  },
  watch: {
    'record.enPortMode': {
      handler (val) {
        this.$nextTick(() => {
          if (val === 1) {
            inputClass(this.$refs, ['VlanId'])
          }
        })
      },
      immediate: true
    },
    'record.PHYSICS_PORT_TYPE': {
      handler (val) {
        if (this.record.enPortMode === 1 && val === 1) {
          this.$nextTick(() => {
            inputClass(this.$refs, ['trVlanId'])
          })
        }
      },
      immediate: true
    }
  },
  methods: {
    init (data) {
      this.dialogVisible = true
      if (data) {
        getBondInfo({ name: data.BondName }).then(res => {
          if (res.status === 0) {
            this.record = Object.assign(this.record, res.info[0])
            this.record.name = this.record.BondName
            // if (typeof this.record.iAllowed === 'object') {
            //   let iAllowed = this.record.iAllowed
            //   this.record.iAllowed = ''
            //   for (const index in iAllowed) {
            //     this.record.iAllowed += index === '0' ? iAllowed[index].AllowedVlanId : (',' + iAllowed[index].AllowedVlanId)
            //   }
            // }
            if (typeof this.record.iAllowed === 'object') {
              let text = ''
              // 修改Trunk VlanId的值用，从1，2，3格式改成1-3
              let newNum = 0 // 如果有连续数字则等于连续数的开始
              let oldNum = 0 // 连续数的末尾
              let flag = false // 进入连续数的标识
              this.record.iAllowed.forEach((item, index) => {
                if (index === 0) { // 初始值
                  newNum = item.AllowedVlanId
                  text += item.AllowedVlanId
                } else {
                  if (flag) {
                    // 进入连续数
                    if (item.AllowedVlanId === (oldNum + 1)) {
                      oldNum = item.AllowedVlanId
                    } else {
                      text += oldNum
                      text += ',' + item.AllowedVlanId
                      newNum = item.AllowedVlanId
                      oldNum = 0
                      flag = false
                    }
                  } else {
                    // 未进入连续数
                    if (item.AllowedVlanId === (newNum + 1)) {
                      flag = true
                      oldNum = item.AllowedVlanId
                      text += '-'
                    } else {
                      newNum = item.AllowedVlanId
                      text += ',' + item.AllowedVlanId
                    }
                  }
                }
              })
              if (flag) {
                text += oldNum
              }
              this.record.iAllowed = text
            }
            for (const index in this.record.ipv4) {
              if (!this.record.ipv4[index].cPortIpv4) {
                this.record.ipv4.splice(index, 1)
                break
              }
            }
            for (const index in this.record.ipv6) {
              if (!this.record.ipv6[index].cPortIpv6) {
                this.record.ipv6.splice(index, 1)
                break
              }
            }
          }
        })
      }
    },
    submit () {
      this.$refs.form.validate((valid) => {
        if (valid) {
          let formData = JSON.parse(JSON.stringify(this.record))
          formData.ipv4 = JSON.stringify(formData.ipv4)
          formData.ipv6 = JSON.stringify(formData.ipv6)
          setBondInfo(formData).then(res => {
            if (res.status === 0) {
              this.$message({
                message: this.$t('配置成功'),
                type: 'success'
              })
              this.close()
              this.$emit('listData')
            }
          })
        }
      })
    },
    close () {
      this.dialogVisible = false
      this.record = Object.assign({}, this.recordCopy)
      this.$refs.form.resetFields()
    },
    addBondIp (type) {
      this.$nextTick(() => {
        this.$refs.refBondIpDialogVisible.init(type)
      })
    },
    addBondIpForTable (data, type) {
      if (type === 'IPv4') {
        this.record.ipv4.push({ cPortIpv4: data.ip, cPortNetmask: data.netmask })
      } else if (type === 'IPv6') {
        this.record.ipv6.push({ cPortIpv6: data.ip, cDevIpv6Prefix: data.prefix })
      }
    },
    deleteRow (index, rows) {
      rows.splice(index, 1)
    },
    handleClick (tab, event) { }
  }
}
</script>
<style scoped>
.dialogContentBox {
  max-height: calc(80vh - 184px);
  overflow-y: auto;
}
</style>
